// 仿照 reducer 的写法
const initialState = {
    count: 0
};

function reducer(state = initialState, action) {
    switch (action.type) {
        case 'plus':
            return {
                ...state,
                count: state.count + 1
            }
        case 'substract':
            return {
                ...state,
                count: state.count - 1
            }
        default:
            return initialState
    }
}

const createStore = (reducer) => {
    // 公共状态
    let currentState = {};

    // 观察者
    let observers = [];

    // getter
    function getState() {
        return currentState;
    }

    // setter   
    function dispatch(action) {
        currentState = reducer(currentState, action);
        observers.forEach(fn => fn());    // 当数据发生变化时，触发对应的方法
    }

    // 发布订阅
    function subscribe(fn) {
        observers.push(fn);
    }

    // 初始化参数
    dispatch({ type: '' })

    return { getState, dispatch, subscribe };
}


// 使用
const store = createStore(reducer);
store.subscribe(() => { console.log(1); });
store.subscribe(() => { console.log(2); });
store.dispatch({ type: 'plus' })

// 1
// 2